<template>
  <view>
    <!-- 视频 -->
    <video id="myVideo" autoplay :poster="videoInfo.coverUrl" :src="videoInfo.contentUrl"
      @timeupdate="videoTimeUpdateEvent" @ended="videoEnd" @play="videoPlay" style="width: 100%;"
      :show-fullscreen-btn="false" :enable-progress-gesture="false" :http-cache="true">
    </video>
    <view class="b-box">
      <!-- 视频标题 -->
      <view class="video-name">{{ videoInfo.contentTitle }}</view>
      <view class="video-desc">
        <view class="video-desc-item">
          <view class="icon"><uni-icons type="info" color="#666"></uni-icons></view>
          <view class="msg">播放完成后才能开始答题</view>
        </view>
        <view class="video-desc-item">
          <view class="icon"><uni-icons type="info" color="#666"></uni-icons></view>
          <view class="msg">答题完成后，点击底部“提交”按钮完成答题</view>
        </view>
      </view>
      <view class="answer" v-for="item in allQuestion">
        <view class="answer-title">{{ item.question }}</view>
        <view class="answer-choose" v-for="itemTwo in item.option"
          :class="{ 'answer-choose-active': isSelect(item.questionId, itemTwo.value) }"
          @click="onSelect(item.questionId, itemTwo.value, item.type)">
          <view class="answer-choose-left">{{ itemTwo.label }}</view>
        </view>
      </view>
      <view class="answer-btn" :style="{opacity: notCanSubmit ? 0.5 : 1}" @click="onSubmit">确定</view>
      <view style="height: 50upx;"></view>
    </view>
  </view>
</template>

<script>
import { imgBasePath, trackingHost } from "@/common/config";
let oldPlayTime = 0;

export default {
  data() {
    return {
      videoId: null, // 视频id
      videoInfo: {}, // 视频答题界面信息
      allQuestion: [],
      activityId: null, // 活动id
      taskId: null,
      taskType: "",
      imgBasePath,
      answerDetail: [],
      isVideoEnd: false,
      startTime: Date.parse(new Date()),
    }
  },
  onLoad(query) {
    const { activityId, taskId, taskType } = query;
    this.activityId = activityId;
    this.taskId = taskId;
    this.taskType = taskType;
    this.getTaskContent();
  },
  onUnload() {
    const endTime = Date.parse(new Date());
    this.videoQATask("sessionTime", (endTime - this.startTime) / 1000);
  },
  onShow() {
    this.videoContext = uni.createVideoContext('myVideo');
  },
  computed: {
    notCanSubmit() {
      return this.answerDetail.length !== this.allQuestion.length || !!this.answerDetail.find(item => !item.option.length);
    }
  },
  methods: {
    videoQATask(event, st) {
      const { unionid, openid } = uni.getStorageSync("userInfo")
      const params = {
        oid: openid,
        uid: unionid,
        cid: this.videoId,
        ts: Date.parse(new Date()) / 1000,
        event,
        page: "videoQATask",
        st
      }
      this.$request("event-tracking/user", { host: trackingHost, params })
        .catch(() => { })
    },
    onSubmit() {
      if(this.notCanSubmit) return;
      const { activityId, taskId, taskType, videoId: contentId, answerDetail } = this;
      const params = {
        activityId,
        taskId,
        taskType,
        contentId,
        submitDataVo: {
          answerDetail
        }
      }
      this.videoQATask("click");
      this.$request("marketing/task/progress", { params })
        .then(res => {
          uni.navigateBack();
        }).catch(() => { })
    },
    isSelect(questionId, answerValue) {
      const findAnswer = this.answerDetail.find(item => item.questionId === questionId);
      return findAnswer && findAnswer.option.includes(answerValue);
    },
    onSelect(questionId, answerValue, type) {
      if (!this.isVideoEnd) return;
      const { answerDetail } = this;
      const findAnswer = answerDetail.find(item => item.questionId === questionId);
      if (findAnswer) {
        if (findAnswer.option.includes(answerValue)) {
          findAnswer.option = findAnswer.option.filter(value => value != answerValue)
        } else {
          if (type === "radio") {
            findAnswer.option = [answerValue];
          } else {
            findAnswer.option.push(answerValue);
          }
        }
      } else {
        answerDetail.push({
          questionId,
          option: [answerValue]
        })
      }
      this.answerDetail = [...answerDetail];
    },
    getTaskContent() {
      const params = {
        activityId: this.activityId,
        taskId: this.taskId,
      }
      this.$request("marketing/task/content", { params, method: "GET" })
        .then(res => {
          const videoInfo = res[0];
          this.videoInfo = videoInfo;
          this.videoId = videoInfo.contentId;
          this.allQuestion = videoInfo.metaDataVo.questionPool;
          this.videoQATask("impression");
          this.setLookStorageTime();
        })
        .catch(err => {})
    },
    // 微信登陆
    wxLogin() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (loginRes) => {
            resolve(loginRes.code)
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    },

    // 检测是否有当前视频的缓存时间节点
    setLookStorageTime() {
      // 获取 - 缓存是否存在当前视频的时长
      const timeNum = uni.getStorageSync(`videoAnswer_${this.videoId}`);
      // 如果存在 设置上次时间
      if (timeNum) {
        setTimeout(() => {
          this.videoContext.seek(Number(timeNum))
          oldPlayTime = timeNum;
        }, 1000)
      }
    },
    // 监听视频不可快进
    videoTimeUpdateEvent(e) {
      let currentTime = Number(e.detail.currentTime);
      // 如果快进 设置为oldTIme
      if ((currentTime - oldPlayTime) > 5) {
        this.videoContext.seek(oldPlayTime)
      } else {
        if (currentTime != 0) {
          // 如果存在上一次的节点 设置为上一次未看完的时间节点
          if (currentTime < 1 && oldPlayTime > 1) {
            this.videoContext.seek(oldPlayTime)
          } else {
            oldPlayTime = currentTime;
            // 存储当前视频播放进度
            uni.setStorageSync(`videoAnswer_${this.videoId}`, currentTime)
          }
        }
      }
    },
    // 视频结束的时候触发
    videoEnd() {
      this.isVideoEnd = true;
      uni.removeStorageSync(`videoAnswer_${this.videoId}`);
    },
    // 视频开始的时候触发
    videoPlay() {},

  },
}
</script>

<style lang="scss" scoped>
.mask {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1;
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.50);
}

.b-box {
  width: 690upx;
  min-height: 10upx;
  margin: 0 auto;
}

.video-name {
  width: 690upx;
  font-size: 36upx;
  font-weight: 500;
  color: #000;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 10upx;
  margin-top: 30upx;
  margin-bottom: 20upx;
}

.video-tag {
  display: inline-block;
  min-width: 10upx;
  height: 54upx;
  line-height: 54upx;
  background: #EA7C0F;
  color: #fff;
  padding: 0 20upx;
  border-radius: 28upx 0upx 28upx 0upx;
}

.video-info {
  min-height: 10upx;
  margin: 30upx 0;
  color: #666;
  font-size: 28upx;
  display: flex;
}

.video-info-time {
  flex: 1;
}

.video-info-num {}

.video-answer-num {
  color: #666;
  font-size: 28upx;
  margin: 30upx 0;
}

.answer {
  min-height: 10upx;
  margin-bottom: 40upx;
}

.answer-title {
  line-height: 48upx;
  color: #333;
  font-weight: 600;
  font-size: 32upx;
  margin-bottom: 30upx;
}

.answer-choose {
  min-height: 10upx;
  background-color: #fff;
  background: #F0F0F0;
  border-radius: 16upx;
  font-size: 36upx;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
  margin-bottom: 20upx;
  padding: 30upx 0;
}

.answer-choose-active {
  background: #ECF6F0;
  color: #219F64;
}

.answer-choose-left {
  flex: 1;
  padding-left: 30upx;
}

.answer-choose-right {
  padding-right: 60upx;
}

.answer-btn {
  width: 690upx;
  height: 100upx;
  line-height: 100upx;
  color: #fff;
  background-color: #00BF90;
  text-align: center;
  border-radius: 50upx;
}

/* 后期添加 */
.video-date {
  width: 100%;
  display: flex;
  margin-bottom: 40upx;
  align-items: center;
}

.video-date-end-date {
  font-size: 34upx;
  font-weight: 500;
  color: #999999;
}

.video-date-value {
  font-size: 34upx;
  color: #EA7C0F;
  font-weight: 500;
}

.video-desc {
  width: 100%;
  background-color: #E2E2E2;
  border-radius: 4upx;
  box-sizing: border-box;
  padding: 16upx;
  margin-bottom: 40upx;
}

.video-desc-item {
  width: 100%;
  display: flex;
  box-sizing: border-box;
  margin-bottom: 8upx;
  color: #666;
  font-size: 30upx;
  align-items: center;
}

.video-desc .icon {
  width: 30upx;
  height: 30upx;
  margin-right: 10upx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
